package cn.lcfms.app.admin.controller;


import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import cn.lcfms.app.admin.bean.AdminBean;
import cn.lcfms.app.admin.bean.RoleBean;
import cn.lcfms.bin.BaseCache;
import cn.lcfms.bin.Userinfo;
import cn.lcfms.bin.annotation.PermitPoll;
import cn.lcfms.bin.core.Application;
import cn.lcfms.bin.service.BaseService;
import cn.lcfms.utils.CommonUtils;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



@PermitPoll(type="系统功能",name="用户管理")
@Controller("admin.UserController")
@RequestMapping("/admin/user")
public class UserController extends AdminBaseController {
	/*
	 * 增加用户组页面
	 */
	@RequestMapping("/add_group_view")
	public String add_group_view(HttpServletRequest request,RoleBean bean) throws ClassNotFoundException{
		ArrayList<String> filelist= Application.getControllerFile();
    	Iterator<String> iterator=filelist.iterator();
    	Set<String[]> permit=new HashSet<>();
    	Set<String> paset=new HashSet<>();
    	while(iterator.hasNext()){
    		String classname=iterator.next();
    		Class<?> cls=Class.forName(classname);
    		if(cls.isAnnotationPresent(PermitPoll.class)==true){
    			PermitPoll poll = cls.getAnnotation(PermitPoll.class);
    			if(poll.type().equals("all")) {
    				continue;
    			}
    			String name=poll.name().equals("")?classname:poll.name();
            	String[] str= {classname,poll.type(),name};  
            	paset.add(poll.type());
            	permit.add(str);
    		}
    		Method[] methods = cls.getMethods();
            for (Method method : methods) {            	
                 if(method.isAnnotationPresent(PermitPoll.class)==true){
                 	 PermitPoll poll = method.getAnnotation(PermitPoll.class);
                 	 if(poll.type().equals("all")) {
        				continue;
        			 }
                 	 String name=poll.name().equals("")?classname+"."+method.getName():poll.name();
                	 String[] str= {classname+"."+method.getName(),poll.type(),name};          	
                	 paset.add(poll.type());
                	 permit.add(str);             	                	
                 }             
            }
    	}   	
		if(bean.getRid()!=0){
			BaseService service = Application.getService("role");
			bean = service.selectOne(RoleBean.class,bean.getRid());	
			service.setTable("permit");
			List<HashMap<String, Object>> list = service.column("controller","item").where("rid", bean.getRid()).selectList();
			request.setAttribute("group", bean);
			HashSet<String> set1=new HashSet<>();
			HashSet<Integer> set2=new HashSet<>();
			for(HashMap<String, Object> map:list) {
				if(map.containsKey("controller") && !map.get("controller").equals("")) {
					set1.add((String)map.get("controller"));
				}
				if(map.containsKey("item") && !map.get("item").equals("")) {
					set2.add((int)map.get("item"));
				}
			}
			request.setAttribute("groupPermit", set1);
			JSON tree = listToTree(BaseCache.ITEMCACHE, 0,set2);
			request.setAttribute("item", tree);
		}else {
			HashSet<Integer> set=new HashSet<>();
			JSON tree = listToTree(BaseCache.ITEMCACHE, 0,set);
			request.setAttribute("item", tree);
		}		
		request.setAttribute("paset", paset);
		request.setAttribute("permit", permit);
		return "admin/frame/roleAdd";
	}	 
	
	private JSON listToTree(List<HashMap<String, Object>> list,int parentId,Set<Integer> set) {
		JSONArray array=new JSONArray();
		for(HashMap<String, Object> map:list) {
			int _id=(int) map.get("itemId");
			int _pid=(int) map.get("parentId");
			String name=(String) map.get("itemName");
			String icon=(String) map.get("icon");
			if(_pid==parentId) {							
				JSONObject object=JSONObject.fromObject(map);	
				object.put("id", _id);
				object.put("pid", _pid);
				object.put("text", name);
				object.put("icon", "iconfont "+icon);
				if(set.contains(_id)) {
					object.put("state", "{\"opened\":true,\"selected\":true}");
				}else {
					object.put("state", "{\"opened\":true}");
				}			
				object.put("children", listToTree(list,_id,set));
				array.add(object);				
			}
		}
		if(array.size()>0) {
			return array;
		}
		return null;
	}
	/*
	 * 查看用户组界面
	 */
	@RequestMapping("/manage_group")
	public String manage_group(HttpServletRequest request) throws Exception{
		BaseService service = Application.getService("role");			
		List<HashMap<String, Object>> list = service.selectList();
		request.setAttribute("list", list);		
		return "admin/frame/roleManage";
	}
    /*
     * 处理修改或增加用户组
     */
	@RequestMapping("/add_group")
	public String add_group(String[] permit,int[] gitem,RoleBean bean){
		BaseService service = Application.getService("role");
		if(bean.getRid()!=0) {
			service.update(bean);
			service.setTable("permit");
			service.where("rid", bean.getRid()).delete();			
		}else {
			service.insert(bean);
		}		
		if(null!=permit) {
			service.setTable("permit");
			for(String p:permit) {
				service.setData(bean.getRid(),p).insert("rid","controller");
			}
		}
		if(null!=gitem) {
			service.setTable("permit");
			for(int g:gitem) {
				service.setData(bean.getRid(),g).insert("rid","item");
			}
		}
		BaseCache.PERMIT=new HashMap<>();
		return "{code:1,msg:保存成功！,url:manage_group}";
	}
	/*
	 * 删除用户组
	 */
	@RequestMapping("/delete_group")
	public String delete_group(int rid){
		BaseService service = Application.getService("role");
		service.deleteById(rid);
		return "local:manage_group";
	}
	/*
	 * 增加或修改用户界面
	 */
	@RequestMapping("/add_update_view")
	public ModelAndView update_user_view(AdminBean bean){
		BaseService service = Application.getService("role");
		List<HashMap<String, Object>> list = service.selectList();
		ModelAndView view=new ModelAndView("admin/frame/userAdd","list",list);
		if(bean.getAid()!=0){			
			bean=service.setTable("admin").selectOne(AdminBean.class, bean.getAid());	
			int[] rid = bean.getRid();
			HashSet<Integer> set=new HashSet<>();
			for(int r:rid) {
				set.add(r);
			}
			view.addObject("rid", set);
		}
		view.addObject("user", bean);
		service.setTable("department");
		List<HashMap<String, Object>> department = service.selectList();
		view.addObject("department", department);
		return view;
	}
	/*
	 * 查看用户界面
	 */
	@RequestMapping("/manage_user")
	public ModelAndView manage_user(){	
		BaseService service = Application.getService("admin");	
		service.leftJoin("department").on("admin.did=department.did");
		List<HashMap<String, Object>> admin = service.column("admin.*,department.dname").selectList();
		service.setTable("role");
		List<HashMap<String, Object>> role = service.selectList();
		HashMap<Integer, String> map=new HashMap<>();
		for(int i=0;i<role.size();i++) {
			int _rid=(int) role.get(i).get("rid");
			String _rname=(String) role.get(i).get("rname");
			map.put(_rid, _rname);
		}
		admin.forEach((HashMap<String, Object> h)->{
			String rid = (String) h.get("rid");
			String[] split = rid.split(",");
			StringBuffer buffer=new StringBuffer();
			for(String s:split) {
				int m=Integer.valueOf(s);
				String str=map.get(m);
				buffer.append(str);
				buffer.append(",");
			}
			h.put("rname", buffer.substring(0, buffer.length()-1));
		});
		ModelAndView view=new ModelAndView("admin/frame/userManage","list",admin);
		return view;
	}
	/*
	 * 处理新增和更新用户
	 */
	@RequestMapping("/add_user")
	public String add_user(String password,AdminBean admin) throws Exception{		 
		BaseService service = Application.getService("admin");		
		if(admin.getAid()!=0){	
			if(password.length()==32){
				service.update(admin,"aname,password");
			}else{	
			    password=CommonUtils.md5(CommonUtils.md5(admin.getAname()+password));
			    admin.setPassword(password);
			    service.update(admin);
			}	
			return "{code:1,msg:修改成功！,url:manage_user}";     
		}else{
			int count = service.where("aname=#{aname}").setData(admin.getAname()).selectCount();
			if(count>0) {
				return "{code:0,msg:登陆名重复！}";   
			}
		    password=CommonUtils.md5(CommonUtils.md5(admin.getAname()+password));
		    admin.setPassword(password);
		    service.insert(admin);
		    return "{code:1,msg:添加成功！,url:manage_user}";     
		}
			
	}
	/*
	 * 禁止用户
	 */
	@RequestMapping("/delete_user")
	public String delete_user(int aid){
		BaseService service = Application.getService("admin");
		service.where("aid", aid).update("status=0");
		return "local:manage_user";  
	}
	/*
	 * 启动用户
	 */
	@RequestMapping("/qiyong_user")
	public String qiyong_user(int aid){
		BaseService service = Application.getService("admin");
		service.where("aid", aid).update("status=1");
		return "local:manage_user";  
	}
	/*
	 * 用户登录
	 */
	@PermitPoll(type="all")
	@RequestMapping("/login")
	public String login(AdminBean admin,HttpServletRequest request,String formUuid,String verifyCode){	
		boolean verify = BaseCache.VerifyFormUuid(formUuid);
		if(!verify) {
			return "{code:0,msg:表单已经过期，请刷新再试！}";
		}
		verify= BaseCache.VerifyCode(formUuid, verifyCode,"img");
		if(!verify) {
			return "{code:0,msg:验证码不正确！}";
		}
		BaseService service= Application.getService();
		Pattern p = Pattern.compile("^1[3|4|5|7|8][0-9]{9}$");	 
		Matcher m = p.matcher(admin.getAname());
		if(m.matches()) {
			service.setData(admin.getAname()).sql("select a.*,b.dname from admin a left join department b on a.did=b.did where a.mobile=#{mobile}");		
		}else {
			service.setData(admin.getAname()).sql("select a.*,b.dname from admin a left join department b on a.did=b.did where a.aname=#{aname}");		
		}	
		List<HashMap<String, Object>> list=service.getResult();
		if(list.size()>0){	
			int index=-1;
			for(int i=0;i<list.size();i++) {
				String aname = (String) list.get(i).get("aname");
				String password=(String) list.get(i).get("password");
				String _password=CommonUtils.md5(CommonUtils.md5(aname+admin.getPassword()));
				if(password.equals(_password)) {
					index=i;
				}
			}
			if(index==-1) {
				return "{code:0,msg:用户名或密码错误！}";
			}
			int status=(int) list.get(index).get("status");
			if(status==0) {
				return "{code:0,msg:该账号已经被禁止使用！}";
			}
			HttpSession session=request.getSession();
			Set<String> key_array=list.get(index).keySet();
			String key=new String();
            Iterator<String> it_1=key_array.iterator();
            while (it_1.hasNext()) {
				key=it_1.next();					
				if(key.equals("password")){
					continue;
				}else if(key.equals("rid")){
					HashSet<Integer> r=new HashSet<>();
					String rid=(String) list.get(index).get(key);
					String[] split = rid.split(",");
					for(String s:split) {
						r.add(Integer.valueOf(s));
					}
					Userinfo.put("rid", r);	
					session.setMaxInactiveInterval(3600);
					session.setAttribute(key, r);
				}else{
					Userinfo.put(key, list.get(index).get(key));					
					session.setMaxInactiveInterval(3600);
					session.setAttribute(key, list.get(index).get(key));
				}							
			}    
            return "{code:1,msg:登陆成功！}";
		}else{
			return "{code:0,msg:账号不存在！}";
		}
	}	
	/*
	 * 用户退出
	 */
	@PermitPoll(type="all")
	@RequestMapping("/quit")
	public void quit(HttpServletRequest request,HttpServletResponse response) throws IOException{
		HttpSession session=request.getSession();
		Enumeration<String> names=session.getAttributeNames();
		while(names.hasMoreElements()){
			String name=names.nextElement();
			session.removeAttribute(name);
		}
		session=null;
		String basePath=(String) request.getAttribute("APP");
		response.sendRedirect(basePath+"admin/common/login");	
	} 
}
